package org.dftproject.lineagelinkage.core;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.dftproject.genesis.data.genealogy.IPerson;

public class VolatileDuplicateRepository implements IDuplicateRepository {
	
	private final Map<IPerson, Set<IPerson>> duplicatesByPerson = Collections.synchronizedMap(new HashMap<IPerson, Set<IPerson>>());

	public Set<IPerson> getPrimaryPersons() {
		synchronized (duplicatesByPerson) {
			return new HashSet<IPerson>(duplicatesByPerson.keySet());
		}
	}
	
	public Set<IPerson> getPotentialDuplicates(IPerson person) {
		synchronized (duplicatesByPerson) {
			Set<IPerson> duplicates = duplicatesByPerson.get(person);
			if (duplicates == null)
				return Collections.emptySet();
			return new HashSet<IPerson>(duplicates);
		}
	}
	
	public void addPotentialDuplicate(IPerson person, IPerson duplicate) {
		synchronized (duplicatesByPerson) {
			Set<IPerson> duplicates = duplicatesByPerson.get(person);
			if (duplicates == null) {
				duplicates = new HashSet<IPerson>();
				duplicatesByPerson.put(person, duplicates);
			}
			duplicates.add(duplicate);
		}
	}

	public void removePotentialDuplicate(IPerson person, IPerson duplicate) {
		synchronized (duplicatesByPerson) {
			Set<IPerson> duplicates = duplicatesByPerson.get(person);
			if (duplicates != null) {
				duplicates.remove(duplicate);
				if (duplicates.isEmpty())
					duplicatesByPerson.remove(person);
			}
		}
	}

	public long getDuplicateCount() {
		synchronized (duplicatesByPerson) {
			long count = 0;
			for (Set<IPerson> duplicates : duplicatesByPerson.values())
				count += duplicates.size();
			return count;
		}
	}

}
